package springmvc.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import Utils.JsonUtil;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class BaseController {

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值，false:不能为空值

	}

	/**
	 * 从thread local获取网络上下文
	 */
	public HttpServletRequest getServletRequest() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes servletRequestAttributes;
		if (requestAttributes instanceof ServletRequestAttributes) {
			servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
			return servletRequestAttributes.getRequest();
		}
		return null;
	}

	public String getResult(Object data, String strMessage, int status) {

		JsonResult result = new JsonResult();

		if (data == null || data.toString().length() == 0) {
			result.setData(data);
			result.setMessage("数据获取错误");
			result.setCode(-1);
		} else {
			result.setData(data);
			result.setMessage(strMessage);
			result.setCode(status);
		}

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().serializeNulls()
				.create();
		return gson.toJson(result);
	}

	public String getResult(Object data, String strMessage) {

		JsonResult result = new JsonResult();

		if (data == null || data.toString().length() == 0) {
			result.setData(data);
			result.setMessage("数据获取错误");
			result.setCode(-1);
		} else {
			result.setData(data);
			result.setMessage(strMessage);

		}

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().serializeNulls()
				.create();
		return gson.toJson(result);
	}

	public String getResult(Object data) {

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().serializeNulls()
				.create();

		JsonResult result = new JsonResult();

		if (data == null || data.toString().length() == 0) {
			result.setData(data);
			result.setMessage("错误");
			result.setCode(-1);
		} else {
			result.setData(data);
			result.setMessage("成功");
			result.setCode(1);

		}
		return gson.toJson(result);
	}

	/**
	 * 获取请求属性封装为Map类型
	 * 
	 * @param request
	 * @return
	 */
	protected HashMap<String, Object> getRequestMapSingle(HttpServletRequest request) {
		HashMap<String, Object> conditions = new HashMap<String, Object>();
		Map map = request.getParameterMap();
		for (Object o : map.keySet()) {
			String key = (String) o;
			conditions.put(key, ((String[]) map.get(key))[0]);
		}
		return conditions;
	}

	public Object getAttribute(String attributeName) {
		return this.getRequest().getAttribute(attributeName);
	}

	public void setAttribute(String attributeName, Object object) {
		this.getRequest().setAttribute(attributeName, object);
	}

	public Object getSession(String attributeName) {
		return this.getRequest().getSession(true).getAttribute(attributeName);
	}

	public void setSession(String attributeName, Object object) {
		this.getRequest().getSession(true).setAttribute(attributeName, object);
	}

	public HttpServletRequest getRequest() {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		return ((ServletRequestAttributes) ra).getRequest();
	}

	public HttpServletResponse getResponse() {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		return ((ServletRequestAttributes) ra).getResponse();
	}

	public HttpSession getSession() {
		return this.getRequest().getSession(true);
	}

	public String getParameter(String paraName) {
		return this.getRequest().getParameter(paraName);
	}

	/**
	 * 获取表单格式数据(或url拼接参数)
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Map getParameterMap() {
		return this.getRequest().getParameterMap();
	}

	public String getHeader(String headerName) {
		return this.getRequest().getHeader(headerName);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map getHeaderMap() {
		Enumeration headerNames = this.getRequest().getHeaderNames();
		Map headerMap = new HashMap<String, Object>();
		while (headerNames.hasMoreElements()) {
			String headerName = (String) headerNames.nextElement();
			String headerValue = getRequest().getHeader(headerName);
			headerMap.put(headerName, headerValue);
		}
		return headerMap;
	}

	public String getIpAddress() {
		// String ip = this.getRequest().getRemoteAddr();
		// return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}

	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 把浏览器参数转化放到Map集合中
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * 
	 *                                      protected Map<String, Object>
	 *                                      getParam(HttpServletRequest request) {
	 *                                      Map<String, Object> paramMap = new
	 *                                      HashMap<String, Object>(); String method
	 *                                      = request.getMethod(); Enumeration<?>
	 *                                      keys = request.getParameterNames();
	 *                                      while (keys.hasMoreElements()) { Object
	 *                                      key = keys.nextElement(); if(key!=null){
	 *                                      if (key instanceof String) { String
	 *                                      value =
	 *                                      request.getParameter(key.toString());
	 *                                      if("GET".equals(method))
	 *                                      {//前台encodeURIComponent('我们');转码后到后台还是ISO-8859-1，所以还需要转码
	 *                                      try { value =new
	 *                                      String(value.getBytes("ISO-8859-1"),"UTF-8");
	 *                                      } catch (UnsupportedEncodingException e)
	 *                                      { e.printStackTrace(); } }
	 *                                      paramMap.put(key.toString(), value); } }
	 *                                      } return paramMap; }
	 * 
	 *                                      //将数据刷新写回web端 protected void
	 *                                      flushResponse(HttpServletResponse
	 *                                      response, String responseContent) {
	 *                                      PrintWriter writer = null; try {
	 *                                      response.setCharacterEncoding("GBK"); //
	 *                                      针对ajax中页面编码为GBK的情况，一定要加上以下两句
	 *                                      response.setHeader("Cache-Control",
	 *                                      "no-cache");
	 *                                      response.setContentType("text/html;charset=UTF-8");
	 *                                      writer = response.getWriter(); if
	 *                                      (responseContent==null ||
	 *                                      "".equals(responseContent) ||
	 *                                      "null".equals(responseContent)) {
	 *                                      writer.write(""); } else {
	 *                                      writer.write(responseContent); } } catch
	 *                                      (IOException e) { throw new
	 *                                      RuntimeException(e); } finally { if
	 *                                      (writer != null) { writer.flush();
	 *                                      writer.close(); } } }
	 * 
	 * 
	 * 
	 * 
	 *                                      /** 获取session对象
	 * @return
	 */
	protected HttpSession getSession(HttpServletRequest request) {
		HttpSession session = request.getSession();
		return session;
	}

	/**
	 * 返回列表分页的下角页码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getPageNumberInfo(int total, int startIndex, int pageSize, ModelAndView result) {
		// Math.ceil整数则为该整数，Math.ceil小数则为靠近大的整数
		int current = (int) Math.ceil((startIndex + 1.0) / pageSize);
		result.addObject("start", startIndex);
		result.addObject("limit", pageSize);
		result.addObject("total", total);
		result.addObject("current", current);
		if (total > 0) {
			int page = (int) Math.ceil(total / pageSize);
			double totald = total;
			if (totald / pageSize > total / pageSize) {
				page = page + 1;
			}
			result.addObject("page", page);
			int startPage = 0;
			int endPage = 0;
			if (page < 8) {
				startPage = 1;
				endPage = page;
			} else {
				if (current < 5) { // 展示前6页
					startPage = 1;
					endPage = 6;// page>6?6:page;
				} else if (page - current < 6) {// 展示最后6页，例如：current=10 page=15
												// 10-15
					startPage = page - 5;
					endPage = page;
				} else {// current=20 18——22
					startPage = current - 2;
					endPage = current + 2;
				}
			}
			result.addObject("startPage", startPage);
			result.addObject("endPage", endPage);
		} else {
			result.addObject("page", 0);
		}
		return result;
	}

	/** * 获取服务器ip地址 * @return */
	public String getServerIpAddress() {
		InetAddress address;
		String serverIpAddress = null;
		try {
			address = InetAddress.getLocalHost(); // 获取的是本地的IP地址
			// PC-20140317PXKX/192.168.0.121
			serverIpAddress = address.getHostAddress();// 192.168.0.121
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return serverIpAddress;
	}

	/** * 获取json格式数据 * @return */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getRequestMap() {
		try {
			InputStream inStream = this.getRequest().getInputStream(); // 默认为json
			BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
			StringBuffer stringBuffer = new StringBuffer();
			String buffer = "";
			while (null != (buffer = (in.readLine()))) {
				stringBuffer.append(buffer);
			}
			String reqDoc = stringBuffer.toString();
			if (reqDoc == null || reqDoc.equals("")) {
				return null;
			}
			return JsonUtil.toMap(reqDoc);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/** * 允许跨域访问 */
	public void allowCrossDomainAccess() {
		HttpServletResponse servletResponse = getResponse();
		servletResponse.setHeader("Access-Control-Allow-Origin", "*");
		servletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET");
		servletResponse.setHeader("Access-Control-Allow-Headers:x-requested-with", "content-type");
	}

}